import functools
from threading import local
import pymysql

thread_local = local()
def connect_db(*, host="192.168.10.107", port=3306, user="coffee", passwd="coffee123456", db="task"):
    """
    获取数据库链接
    :return:
    """
    if not hasattr(thread_local, "_conn"):
        conn = pymysql.connect(
            host=host,
            user=user,
            passwd=passwd,
            database=db,
            cursorclass=pymysql.cursors.DictCursor,
            port=port
        )

        setattr(thread_local, "_conn", conn)

    return getattr(thread_local, "_conn")


def close_db():
    if hasattr(thread_local, "_conn"):

        conn = getattr(thread_local, "_conn")

        if conn:
            conn.close()
            delattr(thread_local, "_conn")


